package org.xiaojl.modules.sys.controller;

import java.util.List;

import javax.validation.Valid;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.xiaojl.common.Constants;
import org.xiaojl.common.SessionUser;
import org.xiaojl.common.base.BaseController;
import org.xiaojl.config.easyui.EasyUITree;
import org.xiaojl.config.easyui.EasyuiUtil;
import org.xiaojl.modules.sys.entity.SysResource;
import org.xiaojl.modules.sys.service.SysResourceService;
import org.xiaojl.utils.ToolUtil;
import org.xiaojl.utils.WebUtil;

import com.baomidou.mybatisplus.mapper.EntityWrapper;

/**
 * <p>
 * 资源 前端控制器
 * </p>
 *
 * @author xiaojl
 * @since 2017-09-11
 */
@Controller
@RequestMapping("/sys/sysResource")
public class SysResourceController extends BaseController {
	private static final Logger log = LoggerFactory.getLogger(SysResourceController.class);
	private static final String basePagePath = "sys/resource/";
	
	@Autowired
	private SysResourceService sysResourceService;
	
	/**
	 * 获取用户菜单树
	 */
	@RequestMapping("/menuTree")
	public @ResponseBody List<EasyUITree> menuTree(){
		SessionUser su = WebUtil.getSessionUser();
		
		List<EasyUITree> list = su.getEasyUIMenuTree();
		
		return list;
	}
	
	/**
	 * 进入当前用户拥有的资源页面
	 */
	@RequestMapping("/sessionUserResourcePage")
	public String sessionUserResourcePage(){
		return basePagePath+"currentUserResource";
	}
	
	/**
	 * 查询当前用户拥有的资源
	 */
	@RequestMapping("/sessionUserResource")
	public @ResponseBody List<EasyUITree> sessionUserResource(){
		SessionUser su = WebUtil.getSessionUser();
		List<SysResource> list = sysResourceService.selectListByUserId(su.getSysUser().getId(),null);
		return EasyuiUtil.resources2ResourceTree(list);
	}
	
	/**
	 * 进入列表页面
	 */
	@RequestMapping("/manager")
	public String manager(){
		return basePagePath+"list";
	}
	
	/**
	 * 查询列表数据
	 */
	@RequiresPermissions("sys/sysResource/manager")
	@RequestMapping("/treeGrid")
	public @ResponseBody Object treeGrid(){
		List<SysResource> list = sysResourceService.selectList(new EntityWrapper<SysResource>().orderBy("seq", true));
		return list;
	}
	
	/**
	 * 所有菜单树
	 */
	@RequestMapping("/allMenuTree")
	public @ResponseBody List<EasyUITree> allMenuTree(){
		List<EasyUITree> list = sysResourceService.selectAllMenuTree();
		return list;
	}
	
	/**
	 * 授权的菜单和按钮(角色授权)<br>
	 * 	1、如果是管理员admin，则查询到所有的菜单和按钮；<br>
	 *  2、如果是普通用户，则只能查询到自己所拥有的菜单和按钮。<br>
	 */
	@RequestMapping("/allResourceTree")
	public @ResponseBody List<EasyUITree> allResourceTree(){
		SessionUser su = WebUtil.getSessionUser();
		if("admin".equals(su.getLoginName())){
			List<EasyUITree> list = sysResourceService.selectAllResourcesTree();
			return list;
		}else{
			List<EasyUITree> list = sysResourceService.selectAllResourcesTreeByUserId(su.getSysUser().getId());
			return list;
		}
	}
	
	@RequiresPermissions("sys/sysResource/add")
	@RequestMapping("/addPage")
	public String addPage(){
		
		return basePagePath+"add";
	}
	
	@RequiresPermissions("sys/sysResource/add")
	@RequestMapping("/add")
	public @ResponseBody Object add(@Valid SysResource entity, BindingResult result, String gnxz){
		try {
			if(result.hasErrors()){
				return operateError(result.getAllErrors().get(0).getDefaultMessage());
			}
			
			/** 数据唯一性校验 */
			List<SysResource> list = sysResourceService.selectList(
						new EntityWrapper<SysResource>()
							.eq("name",entity.getName())
							.eq("resourceType",Constants.SysResource_MENU));
			if(ToolUtil.isNotEmpty(list)){
				return operateError("菜单名称【"+entity.getName()+"】已经存在，请重新命名！");
			}
			//插入数据库
			sysResourceService.insertWithCascade(entity,gnxz);
			
			return operateSuccess("数据添加成功");
		} catch (Exception e) {
			log.error("添加数据出现异常:", e);
			return operateError("保存数据失败");
		}
	}
	
	@RequiresPermissions("sys/sysResource/edit")
	@RequestMapping("/editPage")
	public String editPage(Model model, Long id){
		try {
			SysResource entity = sysResourceService.selectById(id);
			if (ToolUtil.isEmpty(entity)) {
				log.error("获取到的数据为空！id="+id);
			}

			model.addAttribute("entity",entity);
			
		} catch (Exception e) {
			log.error("进入编辑页面时，获取数据出现异常:id="+id, e);
		}
		
		return  basePagePath+"edit" ;
	}
	
	@RequiresPermissions("sys/sysResource/edit")
	@RequestMapping("/edit")
	public @ResponseBody Object edit(@Valid SysResource entity, BindingResult result){
		try {
			if(result.hasErrors()){
				return operateError(result.getAllErrors().get(0).getDefaultMessage());
			}
			
			Long id = entity.getId();
			SysResource oldObj = sysResourceService.selectById(id);
			if (ToolUtil.isEmpty(oldObj)) {
				return operateError("无法获取要修改的数据");
			}
			/** 数据唯一性校验逻辑*/
			if(!oldObj.getName().equals(entity.getName())){
				List<SysResource> list = sysResourceService.selectList(
						new EntityWrapper<SysResource>()
							.eq("name",entity.getName())
							.eq("resourceType",Constants.SysResource_MENU));
				if(ToolUtil.isNotEmpty(list)){
					return operateError("菜单名称【"+entity.getName()+"】已经存在，请重新命名！");
				}
			}
			
			//更新数据库
			sysResourceService.updateById(entity);
			
			return operateSuccess("数据修改成功");
		} catch (Exception e) {
			log.error("保存修改数据出现异常:", e);
			return operateError("数据修改失败");
		}
	}
	
	@RequiresPermissions("sys/sysResource/delete")
	@RequestMapping("/delete")
	public @ResponseBody Object delete(Long id){
		try {
			SysResource entity = sysResourceService.selectById(id);
			if (ToolUtil.isEmpty(entity)) {
				return operateError("无法获取要删除的数据");
			}
			
			sysResourceService.deleteById(id);
			
			return operateSuccess("数据删除成功");
		} catch (Exception e) {
			log.error("删除出现异常:id="+id, e);
			return operateError("数据删除失败");
		}
	}
	
}
